<template>
  <div class="app-container">
    <!-- 计划申报 -->
    <el-card shadow="hover" header="计划申报" class="flex1 h" v-loading="planLoading">
      <div class="disf dirc h pr30">
        <el-form ref="planFormRef" :model="formData" :rules="rules" label-width="100px">
          <el-form-item label="合同名称" prop="name">{{ name }}</el-form-item>
          <el-form-item label="流程模板" prop="flowId">
            <el-select v-model="formData.flowId" placeholder="请选择" style="width: 260px">
              <el-option v-for="item in flowOptions" :key="item.id" :label="item.name" :value="item.id" />
            </el-select>
            <el-button type="primary" plain class="ml15" @click="handleChange">生成流程</el-button>
          </el-form-item>
          <el-form-item label="项目流程">
            <el-button type="primary" plain icon="edit" @click="handleEdit">编辑流程</el-button>
          </el-form-item>
        </el-form>
        <el-scrollbar always class="flex1 ml100" v-if="activityId">
          <div class="flow-node-wrap" v-loading="flowLoading">
            <!-- 遍历：节点列表 -->
            <template v-for="(node, idx) in nodeList" :key="node.id">
              <div class="flow-node">
                <!-- 节点名称 -->
                <div class="node-name">
                  <div class="node-index ml25">{{ idx + 1 }}</div>
                  <div class="disf dirc flex1 w0 plr15">
                    <b>{{ node.name }}</b>
                    <span class="node-remark" :title="node.remark">
                      {{ node.remark || "暂无描述" }}
                    </span>
                  </div>
                  <el-tag type="primary" effect="plain" class="node-tag mr15">
                    {{ FLOW_NODE_TYPE_LABEL[node.nodeType] }}
                    <el-tooltip v-if="node.nodeType == FlowNodeType.AUDITOR_NODE" :content="getAuditBackName(node)"
                      placement="top">
                      <el-icon style="cursor: pointer">
                        <QuestionFilled />
                      </el-icon>
                    </el-tooltip>
                  </el-tag>
                </div>
                <!-- 节点任务列表 -->
                <ol class="node-tasks">
                  <li class="task-line" v-for="task in node.tasks">
                    <div class="task-title">
                      <b>{{ task.name }}</b>
                      <span class="role-icon">
                        <el-icon class="mr5">
                          <User />
                        </el-icon>
                        {{ FLOW_ACT_ROLE_LABEL[task.activityRole] }}
                      </span>
                    </div>
                    <div class="task-remark" :title="task.remark">
                      <span>{{ task.remark }}</span>
                    </div>
                    <div class="task-remark disf alc">
                      <el-icon class="mr5">
                        <Postcard />
                      </el-icon>
                      {{ FLOW_CANDIDAT_TYPE_LABEL[task.candidateType] }}【{{ task.candidateName }}】
                    </div>
                    <div class="task-remark disf alc juend">
                      <el-button size="small" link icon="warning" type="primary" @click="handleDtlTask(task.id)">
                        详情
                      </el-button>
                      <el-button size="small" link icon="edit" type="primary" @click="handleEditTask(node, task.id)">
                        编辑
                      </el-button>
                      <el-button size="small" link icon="delete" type="danger" @click="handleDelTask(task)">
                        删除
                      </el-button>
                    </div>
                  </li>
                  <li class="flow-add-button" @click="handleEditTask(node)">+ 添加任务</li>
                </ol>
              </div>
            </template>
          </div>
        </el-scrollbar>
        <el-empty v-else description="暂无数据，请编辑流程添加节点"></el-empty>
        <div class="disf mt30 alc juc">
          <el-button type="primary" @click="handleSubmit">提交申报</el-button>
        </div>
      </div>
    </el-card>
    <!-- 弹窗：编辑流程 -->
    <Edit :data="dialog.data" :visible="dialog.visible" @dialogClose="closeEdit"></Edit>
    <!-- 弹窗：编辑节点任务 -->
    <EditTask :id="dialogTask.id" :activityId="activityId" :nodeType="dialogTask.nodeType" :nodeId="dialogTask.nodeId"
      :visible="dialogTask.visible" @dialogClose="closeEditTask"></EditTask>
    <!-- 弹窗：查询节点任务 -->
    <TaskDetail :id="dialogTaskDtl.id" :visible="dialogTaskDtl.visible" @dialogClose="closeDtlTask"></TaskDetail>
  </div>
</template>

<script lang="ts" setup>
import FlowAPI, { FlowPageVO } from "@/api/flow/flow.api";
import { FLOW_AUDIT_TYPE_LABEL, FLOW_NODE_TYPE_LABEL, FlowNodeType } from "@/api/flow/flowNode.api";
import Edit from "./components/edit.vue";
import EditTask from "./components/taskEdit.vue";
import TaskDetail from "./components/taskDetail.vue";
import { FLOW_ACT_ROLE_LABEL, FLOW_CANDIDAT_TYPE_LABEL } from "@/api/flow/flowNodeTask.api";
import BuildAPI, { BuildActivityForm, BuildActivitySubmitForm, ContractBuildStatus } from "@/api/flow/build.api";
import { cloneDeep } from "lodash-es";
import { decryptDES, encryptDES } from "@/utils/des";
import ActivityAPI, { ActivityDetail } from "@/api/flow/activity.api";
import { ActivityNodeVO } from "@/api/flow/activityNode.api";
import ActivityNodeTaskAPI, { ActivityNodeTaskVO } from "@/api/flow/activityNodeTask.api";
import { useTagsViewStore } from "@/store";
import router from "@/router";

defineOptions({
  name: "BuildPlanEdit",
  inheritAttrs: false,
});

const route = useRoute();
const tagsViewStore = useTagsViewStore();

const infoKey = ref(""); // 加密参数
const id = ref(""); // 合同id
const name = ref(""); // 合同名称
const activityId = ref(""); //流程实例id
const activityInfo = ref(); //流程实例对象
const nodeList = ref<ActivityNodeVO[]>([]); //节点列表

const planLoading = ref(false);
const flowLoading = ref(false);

const planFormRef = ref();

// 表格数据
const defaultFormData = {
  contractId: "",
  flowId: "",
};
const formData = reactive<BuildActivityForm>(cloneDeep(defaultFormData));
const rules = reactive({
  majorUserId: [{ required: true, message: "请选择负责人", trigger: "blur" }],
  userIds: [{ required: true, message: "请选择参与人", trigger: "blur" }],
});
const flowOptions = ref<FlowPageVO[]>([]); // 流程列表

onMounted(() => {
  FlowAPI.getOptions().then((data) => {
    flowOptions.value = data;
  });
});

onActivated(async () => {
  if (route.query.key == infoKey.value) return;
  // id变动 重置数据
  infoKey.value = route.query.key as string;
  // 提取转换密文对象
  const str = decryptDES(infoKey.value);
  const busiInfo = JSON.parse(str) || {}; //业务信息
  id.value = busiInfo.id;
  name.value = busiInfo.name;
  // 获取实例id和详情
  planLoading.value = true;
  try {
    const contractBuild = await BuildAPI.loadDetail(id.value);
    activityId.value = contractBuild.activityId;
    activityId.value && loadFlowDetail();
  } catch (error) {
    console.log(error);
  }
  planLoading.value = false;
});

/**
 * 切换选中的模板
 */
async function handleChange() {
  flowLoading.value = true;
  const activity = await BuildAPI.bind({ ...formData, contractId: id.value });
  activityId.value = activity.id || "";
  flowLoading.value = false;
  loadFlowDetail();
}

// 加载详情
const loadFlowDetail = () => {
  if (!activityId.value) {
    nodeList.value = [];
    return;
  }
  flowLoading.value = true;
  // 加载流程
  ActivityAPI.load(activityId.value)
    .then((data) => {
      formData.flowId = data.flowId;
      activityInfo.value = data;
      nodeList.value = data.activityNodes;
    })
    .finally(() => {
      flowLoading.value = false;
    });
};

// 获取审核回退的节点
function getAuditBackName(node: ActivityNodeVO) {
  const backNode = nodeList.value.find((item) => item.id == node.backNodeId);
  return `审核方式：${FLOW_AUDIT_TYPE_LABEL[node.auditorType!]}，审核不通过回退至：${backNode?.name}`;
}

/**
 * 新增/编辑弹窗
 */
const dialog = reactive<{
  visible: boolean;
  data?: ActivityDetail;
}>({
  visible: false,
});

function handleEdit() {
  dialog.visible = true;
  dialog.data = cloneDeep(activityInfo.value);
}

// 关闭弹窗
function closeEdit(isRefresh?: boolean) {
  dialog.visible = false;
  // 刷新节点
  isRefresh && loadFlowDetail();
}

/**
 * 新增/编辑 任务弹窗
 */
const dialogTask = reactive<{
  visible: boolean;
  nodeId: string;
  nodeType?: string;
  id?: string;
}>({
  visible: false,
  nodeId: "",
});

function handleEditTask(node: ActivityNodeVO, id?: string) {
  dialogTask.visible = true;
  dialogTask.id = id;
  dialogTask.nodeId = node.id!;
  dialogTask.nodeType = node.nodeType;
}

// 关闭任务弹窗
function closeEditTask(isRefresh?: boolean) {
  dialogTask.visible = false;
  if (isRefresh) {
    loadFlowDetail();
  }
}

/**
 * 任务详情弹窗
 */
const dialogTaskDtl = reactive<{
  visible: boolean;
  id?: string;
}>({
  visible: false,
});

function handleDtlTask(id?: string) {
  dialogTaskDtl.visible = true;
  dialogTaskDtl.id = id;
}

function closeDtlTask() {
  dialogTaskDtl.visible = false;
}

/**
 * 删除任务
 */
function handleDelTask(task?: ActivityNodeTaskVO) {
  if (!task) return;
  ElMessageBox.confirm(`确认删除任务【${task.name}】?`, "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(() => {
    ActivityNodeTaskAPI.deleteById(task.id!).then(() => {
      ElMessage.success("删除成功");
      loadFlowDetail();
    });
  });
}

/**
 * 提交申请
 */
function handleSubmit() {
  ElMessageBox.confirm("确认提交计划申报?", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(() => {
    submit();
  });
}
function submit() {
  planLoading.value = true;
  const sendData: BuildActivitySubmitForm = {
    contractId: id.value,
    subMark: "",
  };
  BuildAPI.subApproval(sendData)
    .then(async () => {
      ElMessage.success("计划申报提交成功");
      await tagsViewStore.closeCurrentView();
      toDetail();
    })
    .finally(() => (planLoading.value = false));
}

/** 跳转详情页面 */
function toDetail() {
  // 参数加密
  const param = { id: id.value, name: name.value };
  const jsonString = JSON.stringify(param);
  const paramStr = encryptDES(jsonString);
  // 路由跳转
  router.push({ path: "/build/plan/detail", query: { key: paramStr } });
}
</script>

<style lang="scss" scoped>
:deep(.el-card__body) {
  height: calc(100% - 70px);
}

.temp-item {
  border: 1px solid #eee;
  border-radius: 5px;
  padding: 10px 14px;
  margin-bottom: 10px;
  cursor: pointer;
  transition: all 0.3s ease-in-out;

  p {
    padding-bottom: 3px;
  }

  span {
    font-size: 0.75em;
    color: #999;
  }

  &:hover {
    border-color: #ccc;
    box-shadow: 3px 3px 5px #ccc;
  }

  &.active {
    border-color: var(--el-color-primary);

    p {
      color: var(--el-color-primary);
      font-weight: bold;
    }

    span {
      color: #666;
    }
  }
}

.flow-node-wrap {
  display: flex;
  white-space: nowrap;
}

.flow-node {
  display: flex;
  width: 18em;
  flex-shrink: 0;
  margin-right: 16px;
  margin-bottom: 15px;
  flex-direction: column;
  font-size: 0.9em;

  .node-name {
    display: flex;
    align-items: center;
    padding: 5px 10px;
    margin-right: -20px;
    // background-color: var(--el-bg-color-page);
    background: url("data:image/svg+xml;charset=utf-8,%3Csvg t='1755228742853' class='icon' viewBox='0 0 1702 1024' version='1.1' xmlns='http://www.w3.org/2000/svg' p-id='15610' data-spm-anchor-id='a313x.search_index.0.i8.6e8f3a81r1hw4J' width='60' height='60'%3E%3Cpath d='M1701.385 541.177l-230.083-234.545H0l216.77 233.967L0 776.004h1471.302z' p-id='15611' data-spm-anchor-id='a313x.search_index.0.i7.6e8f3a81r1hw4J' class='' fill='%23d9e6ff'%3E%3C/path%3E%3C/svg%3E") no-repeat right 52% / 105% auto;
    margin-bottom: 7px;

    .node-index {
      font-size: 1.6em;
      font-weight: bold;
      color: #fff;
      text-shadow: 1px 1px 4px #999;
    }

    .node-remark {
      font-size: 0.75em;
      color: #aaa;
      white-space: nowrap;
      /* 防止文本换行 */
      overflow: hidden;
      /* 隐藏超出部分的文本 */
      text-overflow: ellipsis;
      /* 显示省略号 */
    }

    .node-tag {
      background: none;
    }
  }

  .node-tasks {
    flex: 1;
    padding: 12px 7px 5px;
    background-color: #f3f4fb;
    border-radius: 7px;

    .task-line {
      padding: 5px 10px;
      background-color: #fff;
      border-radius: 9px;
      margin-bottom: 9px;

      .task-title {
        display: flex;
        justify-content: space-between;
        align-items: center;

        .role-icon {
          display: flex;
          align-items: center;
          color: #999;
          font-size: 0.8em;
        }
      }

      .task-remark {
        font-size: 0.75em;
        margin-top: 5px;
        white-space: nowrap;
        /* 防止文本换行 */
        overflow: hidden;
        /* 隐藏超出部分的文本 */
        text-overflow: ellipsis;
        /* 显示省略号 */
      }
    }
  }
}

/* 添加按钮 */
.flow-add-button {
  border: 1px dashed #d1d1d1;
  border-radius: 5px;
  padding: 15px;
  background-color: #fff;
  border-radius: 9px;
  margin-bottom: 9px;
  font-weight: bold;
  cursor: pointer;
  color: #9e9e9e;
  transition: all 0.3s ease-in-out;

  &:hover {
    border-color: var(--el-color-primary);
    color: var(--el-color-primary);
  }
}
</style>
